{% extends 'base.html' %}

{% block title %}
预约核销
{% endblock %}

{% block content %}
<div class="container mt-5">
    <h2 class="text-center mb-4">预约核销</h2>
    
    <!-- 查询区域 -->
    <div class="row justify-content-center mb-5">
        <div class="col-md-8">
            <div class="card shadow-sm">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0"><i class="bi bi-search me-2"></i>查询预约信息</h4>
                </div>
                <div class="card-body">
                    <form method="POST" id="searchForm">
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label for="phone" class="form-label">手机号</label>
                                <input type="text" class="form-control" id="phone" name="phone" placeholder="请输入手机号">
                            </div>
                            <div class="col-md-4">
                                <label for="id_number" class="form-label">证件号码</label>
                                <input type="text" class="form-control" id="id_number" name="id_number" placeholder="请输入证件号码">
                            </div>
                            <div class="col-md-4">
                                <label for="name" class="form-label">姓名</label>
                                <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-8">
                                <label for="order_number" class="form-label">订单号</label>
                                <input type="text" class="form-control" id="order_number" name="order_number" placeholder="请输入订单号">
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="bi bi-search me-1"></i> 查询
                                </button>
                            </div>
                        </div>
                    </form>
                    <div class="text-center mt-3">
                        <button id="scanBtn" class="btn btn-secondary btn-lg" onclick="startScan()">
                            <i class="bi bi-camera me-2"></i> 扫码核销
                        </button>
                        <p class="text-muted mt-2">* 扫码核销将打开摄像头，用于扫描预约成功页面的二维码</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 扫码区域 (默认隐藏) -->
    <div id="scanArea" class="row justify-content-center mb-5" style="display: none;">
        <div class="col-md-8 mx-auto">
            <div class="card shadow">
                <div class="card-header bg-info text-white">
                    <h4 class="mb-0"><i class="bi bi-camera me-2"></i>扫码核销</h4>
                </div>
                <div class="card-body">
                    <div class="text-center mb-3">
                        <button class="btn btn-danger" onclick="stopScan()">
                            <i class="bi bi-x-circle me-1"></i> 停止扫描
                        </button>
                    </div>
                    <div class="d-flex justify-content-center">
                        <div class="text-center" style="max-width: 500px; width: 100%;">
                            <video id="video" width="100%" height="auto" class="rounded border border-2 border-info"></video>
                            <div class="text-center mt-3 text-muted">
                                <p>请将二维码对准摄像头区域</p>
                            </div>
                        </div>
                    </div>
                    <canvas id="canvas" style="display: none;"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 手动输入二维码区域 (默认隐藏) -->
    <div id="manualInputArea" class="row justify-content-center mb-5" style="display: none;">
        <div class="col-md-6">
            <div class="card shadow">
                <div class="card-header bg-warning text-dark">
                    <h4 class="mb-0"><i class="bi bi-keyboard me-2"></i>手动输入</h4>
                </div>
                <div class="card-body">
                    <h5 class="card-title text-center mb-3">手动输入二维码内容</h5>
                    <div class="mb-3">
                        <label for="manualCode" class="form-label">二维码内容</label>
                        <input type="text" class="form-control" id="manualCode" placeholder="请输入二维码中的订单号">
                    </div>
                    <div class="text-center">
                        <button class="btn btn-primary" onclick="submitManualCode()">
                            <i class="bi bi-check-circle me-1"></i> 提交
                        </button>
                        <button class="btn btn-secondary ms-2" onclick="stopScan()">
                            <i class="bi bi-x-circle me-1"></i> 取消
                        </button>
                    </div>
                    <div class="text-center mt-3 text-muted">
                        <p>在无法使用摄像头时，可手动输入二维码中的订单号</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 查询结果区域 -->
    <div class="row justify-content-center">
        <div class="col-md-8">
            {% if bookings %}
                <h3 class="text-center mb-4"><i class="bi bi-list-check me-2"></i>查询结果</h3>
                <div class="booking-results">
                    {% for booking in bookings %}
                    <div class="card mb-4 shadow-sm">
                        <div class="card-header bg-light d-flex justify-content-between align-items-center">
                            <h5 class="mb-0"><i class="bi bi-ticket-detailed me-2"></i>预约记录 #{{ loop.index }}</h5>
                            <span class="badge bg-{% if booking.is_valid %}success{% else %}secondary{% endif %} py-2 px-3">
                                {{ '有效' if booking.is_valid else '已核销' }}
                            </span>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <strong><i class="bi bi-receipt me-2"></i>订单号:</strong> 
                                        <span class="text-primary">{{ booking.order_number }}</span>
                                    </div>
                                    <div class="mb-3">
                                        <strong><i class="bi bi-trophy me-2"></i>赛事名称:</strong> 
                                        {{ booking.event.name }}
                                    </div>
                                    <div class="mb-3">
                                        <strong><i class="bi bi-person me-2"></i>预约人:</strong> 
                                        {{ booking.name }}
                                    </div>
                                    <div class="mb-3">
                                        <strong><i class="bi bi-phone me-2"></i>手机号:</strong> 
                                        {{ booking.phone }}
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <strong><i class="bi bi-card-text me-2"></i>证件类型:</strong> 
                                        {{ booking.id_type }}
                                    </div>
                                    <div class="mb-3">
                                        <strong><i class="bi bi-credit-card me-2"></i>证件号码:</strong> 
                                        {{ booking.id_number }}
                                    </div>
                                    <div class="mb-3">
                                        <strong><i class="bi bi-calendar me-2"></i>预约日期:</strong> 
                                        <span class="text-info">{{ booking.booking_date.strftime('%Y-%m-%d') }}</span>
                                    </div>
                                    <div class="mb-3">
                                        <strong><i class="bi bi-clock me-2"></i>预约时间:</strong> 
                                        {{ booking.created_at.strftime('%H:%M:%S') }}
                                    </div>
                                </div>
                            </div>
                            
                            <div class="text-center mt-4">
                                {% if booking.is_valid %}
                                    {% if booking.booking_date == today %}
                                        <a href="{{ url_for('verify', order_number=booking.order_number) }}" 
                                           class="btn btn-lg btn-primary px-4" 
                                           onclick="return confirm('确定要核销该订单吗？')">
                                            <i class="bi bi-check-circle me-2"></i> 核销入场
                                        </a>
                                    {% else %}
                                        <button class="btn btn-lg btn-outline-secondary px-4" disabled>
                                            <i class="bi bi-calendar-x me-2"></i> 非当天预约
                                        </button>
                                    {% endif %}
                                {% else %}
                                    <button class="btn btn-lg btn-outline-secondary px-4" disabled>
                                        <i class="bi bi-check-circle-fill me-2"></i> 已核销
                                    </button>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            {% elif request.method == 'POST' %}
                <div class="alert alert-info text-center py-3" role="alert">
                    <i class="bi bi-info-circle-fill me-2"></i> 未找到匹配的预约记录
                </div>
            {% endif %}
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
<script>
// 扫码功能实现
let video = null;
let canvas = null;
let context = null;
let stream = null;

function startScan() {
    document.getElementById('searchForm').style.display = 'none';
    document.getElementById('scanArea').style.display = 'block';
    document.getElementById('manualInputArea').style.display = 'none';

    video = document.getElementById('video');
    canvas = document.getElementById('canvas');
    context = canvas.getContext('2d');

    // 检测浏览器是否支持媒体设备API
    // 处理不同浏览器的兼容性问题
    navigator.getUserMedia = navigator.getUserMedia || 
                           navigator.webkitGetUserMedia || 
                           navigator.mozGetUserMedia || 
                           navigator.msGetUserMedia;

    if (!navigator.mediaDevices && navigator.getUserMedia) {
        // 旧版浏览器兼容模式
        mediaDevices = {}
        mediaDevices.getUserMedia = function(constraints) {
            return new Promise(function(resolve, reject) {
                navigator.getUserMedia(constraints, resolve, reject);
            });
        }
    } else if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        alert('您的浏览器不支持摄像头访问功能，请使用Chrome、Firefox、Safari等现代浏览器');
        showManualInput();
        return;
    }

    const mediaDevices = navigator.mediaDevices;

    // 获取摄像头权限
    mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
        .then(function(mediaStream) {
            stream = mediaStream;
            video.srcObject = stream;
            video.setAttribute('playsinline', true);
            video.play();
            requestAnimationFrame(tick);
        })
        .catch(function(err) {
            console.error('获取摄像头失败: ' + err);
            handleCameraError(err);
        });

    // 添加窗口关闭或刷新时停止摄像头的处理
    window.addEventListener('beforeunload', stopScan);

    // 添加页面切换到后台时暂停摄像头的处理
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            video.pause();
        } else if (stream) {
            video.play();
        }
    });
}

function handleCameraError(err) {
    // 根据不同错误类型提供更具体的提示
    let errorMsg = '获取摄像头失败: ';
    if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
        errorMsg += '摄像头权限被拒绝，请在浏览器设置中启用摄像头权限';
    } else if (err.name === 'NotFoundError') {
        errorMsg += '未找到摄像头设备';
    } else if (err.name === 'NotReadableError') {
        errorMsg += '摄像头被其他应用占用';
    } else {
        errorMsg += '未知错误，请重试';
    }
    alert(errorMsg);
    showManualInput();
}

function showManualInput() {
    // 显示手动输入选项
    document.getElementById('scanArea').style.display = 'none';
    document.getElementById('manualInputArea').style.display = 'block';
}

function stopScan() {
    document.getElementById('searchForm').style.display = 'block';
    document.getElementById('scanArea').style.display = 'none';
    document.getElementById('manualInputArea').style.display = 'none';

    if (stream) {
        stream.getTracks().forEach(track => track.stop());
        stream = null;
    }
}

function tick() {
    if (video.readyState === video.HAVE_ENOUGH_DATA) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
        // 使用jsQR库识别二维码
        const code = jsQR(imageData.data, imageData.width, imageData.height);

        if (code) {
            // 如果识别到二维码
            const scannedText = code.data;
            console.log('扫描结果:', scannedText);

            // 直接提交加密的订单号，在后端进行解密
            document.getElementById('order_number').value = scannedText;
            document.getElementById('searchForm').submit();
            stopScan();
        }
    }
    requestAnimationFrame(tick);
}

// 手动输入二维码内容
function submitManualCode() {
    const manualCode = document.getElementById('manualCode').value;
    if (manualCode) {
        document.getElementById('order_number').value = manualCode;
        document.getElementById('searchForm').submit();
        stopScan();
    } else {
        alert('请输入二维码内容');
    }
}
</script>

<style>
    .card {
        border-radius: 12px;
        overflow: hidden;
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    
    .card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.12);
    }
    
    .card-header {
        padding: 1rem 1.5rem;
        font-weight: 600;
    }
    
    .booking-results .card-header {
        background: linear-gradient(135deg, #f8f9fa, #e9ecef);
    }
    
    .badge {
        font-size: 1rem;
        padding: 0.6em 1em;
        border-radius: 12px;
    }
    
    .bg-success {
        background-color: #28a745 !important;
    }
    
    .bg-secondary {
        background-color: #6c757d !important;
    }
    
    #video {
        border: 2px solid #0dcaf0;
        background-color: #f8f9fa;
        border-radius: 8px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    .btn-lg {
        padding: 0.75rem 1.5rem;
        font-size: 1.1rem;
        border-radius: 12px;
    }
    
    .form-control {
        border-radius: 8px;
        padding: 0.75rem;
    }
    
    .text-primary {
        font-weight: 500;
    }
    
    .text-info {
        font-weight: 500;
        color: #0dcaf0 !important;
    }
    
    .alert {
        border-radius: 12px;
    }
    
    .booking-results .card-body {
        padding: 1.5rem;
    }
    
    .mb-3 {
        padding: 0.5rem 0;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .booking-results .card:last-child {
        margin-bottom: 0;
    }
</style>
{% endblock %}